/*
 * @Author: 飞越疯人院 353362604@qq.com
 * @Date: 2022-10-13 09:41:28
 * @LastEditors: 飞越疯人院 353362604@qq.com
 * @LastEditTime: 2022-11-18 16:58:52
 * @FilePath: \adminstration\src\Common\Modal\MoreModal\EditTableModal.jsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { EditableProTable } from '@ant-design/pro-components'
import { useBoolean, useLatest } from 'ahooks'
import { Button, message, Spin } from 'antd'
import axios from 'axios'
import { useState, useEffect } from 'react'
import { v4 as uuidv4 } from 'uuid'

export const EditTableModal = ({ CurrentData, Scroll }) => {
    const [loading, { setTrue, setFalse }] = useBoolean(true)
    const [dataSource, setDataSource] = useState([])
    const [editableKeys, setEditableRowKeys] = useState()
    const dataSourceLatest = useLatest(dataSource)
    useEffect(() => {
        axios.get(CurrentData.get).then(({ data }) => {
            if (typeof data.customData === 'string') {
                let list = JSON.parse(data.customData)
                setDataSource(list)
                setEditableRowKeys(list.map(item => item.uuid))
            }
            setFalse()
        })
    }, [CurrentData.get, dataSourceLatest, setFalse])

    return (
        <Spin spinning={loading}>
            <EditableProTable
                rowKey="uuid"
                columns={CurrentData.columns}
                scroll={Scroll}
                value={dataSource}
                onChange={setDataSource}
                recordCreatorProps={{ newRecordType: 'dataSource', record: () => ({ uuid: uuidv4() }) }}
                toolBarRender={() => {
                    return [
                        <Button
                            type="primary"
                            key="save"
                            onClick={() => {
                                setTrue()
                                let data = dataSource.filter(v => v.one)
                                axios.put(`${CurrentData.put}`, { customData: JSON.stringify(data) }).then(() => {
                                    message.success('数据添加成功')
                                    setFalse()
                                })
                            }}
                        >
                            保存数据
                        </Button>,
                    ]
                }}
                editable={{
                    type: 'multiple',
                    editableKeys,
                    actionRender: (_, __, defaultDoms) => [defaultDoms.delete],
                    onValuesChange: (_, recordList) => setDataSource(recordList),
                    onChange: editableKeys => setEditableRowKeys(editableKeys),
                }}
            />
        </Spin>
    )
}
